package fr.irit.etracetool.etrace.util;

import org.eclipse.emf.ecore.resource.Resource;

import fr.irit.etracetool.etrace.AbstractLink;
import fr.irit.etracetool.etrace.CompositeLink;
import fr.irit.etracetool.etrace.ETrace;
import fr.irit.etracetool.etrace.Link;
import fr.irit.etracetool.query.Predicate;

public class ETraceToText {

	private ETrace trace;

	private Predicate predicate;
	
	public ETraceToText(Resource source, Resource target, ETrace trace) {
		super();
		this.trace = trace;
		predicate = new Predicate(source,target, trace);
	}
	
	public String generate() {
		StringBuffer sb = new StringBuffer();
		generateText(trace, sb, "");
		return sb.toString();
	}

	private void generateText(CompositeLink cl, StringBuffer sb, String prefix) {
		sb.append(prefix + "CompositeLink : ");
		if (cl.getType() != null) {
			sb.append(cl.getType().getName()+"\n");
		} else sb.append("\n");
		prefix += "\t";
		for (AbstractLink al : cl.getChildren()) {
			if (al instanceof Link) {
				sb.append(((Link) al).toString(prefix)+ " \n"+ prefix +getType(al).toString()+ " "+ al.getType().getName()+ "\n");
				//sb.append(prefix + "\t Link : " + ((Link) al).getType().getName() + " " + getType(al).toString() +"\n");
			}
			if (al instanceof CompositeLink) {
				generateText((CompositeLink) al, sb, prefix);
			}
		}
	}

	private StringBuffer getType(AbstractLink al) {
		StringBuffer sb = new StringBuffer();
		if (predicate.sourcePredicate(al.getSource())) sb.append("source -->");
		if (predicate.targetPredicate(al.getSource())) sb.append("target -->");
		if (predicate.intermediatePredicate(al.getSource())) sb.append("intermediate -->");
		if (predicate.sourcePredicate(al.getTarget())) sb.append(" source");
		if (predicate.targetPredicate(al.getTarget())) sb.append(" target");
		if (predicate.intermediatePredicate(al.getTarget())) sb.append(" intermidiate");

		return sb;
	}
}
